package spring.cloud.tasks.tasks_manager.tasks_manager.listener;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;
import spring.cloud.tasks.tasks_manager.tasks_manager.node.Node;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.AllotTaskItemService;

@Slf4j
@Setter
@Getter
public class ExecutorLostOrRecoverTrafficListener extends TreeCacheListener {
    private AllotTaskItemService allotTaskItemService;

    public ExecutorLostOrRecoverTrafficListener(AllotTaskItemService allotTaskItemService) {
        this.allotTaskItemService = allotTaskItemService;
    }

    @Override
    public void childEvent(Type type, String path, String nodeData) throws Exception {
        try {
            if (isExecutorLostTraffic(type, path)) {
                String executorName = Node.getExecutorNameByNoTrafficPath(path);
                allotTaskItemService.executorLostTrafficAllotTask(executorName);
            } else if (isExecutorRecoverTraffic(type, path)) {
                String executorName = Node.getExecutorNameByNoTrafficPath(path);
                allotTaskItemService.executorRecoverTrafficAllotTask(executorName);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private boolean isExecutorLostTraffic(Type type, String path) {
        return type == Type.NODE_ADDED && path.matches(Node.EXECUTOR_LOST_TRAFFIC_NODE_PATH_REGEX);
    }

    public boolean isExecutorRecoverTraffic(Type type, String path) {
        return type == Type.NODE_REMOVED && path.matches(Node.EXECUTOR_LOST_TRAFFIC_NODE_PATH_REGEX);
    }

}